package com.lvt.design.pattern.module.auth.token;

import com.lvt.design.pattern.module.auth.apirequest.ApiRequest;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

/**
 * @author LT
 * @date 2023年02月21日 23:14
 */
public class AuthToken {
    private String token;
    private long createTime;
    private static final long DEFAULT_EXPIRED_TIME_INTERVAL = 1*60*1000;
    private long expiredTimeInterval = DEFAULT_EXPIRED_TIME_INTERVAL;

    public AuthToken(String token) {
        this.token = token;
    }

    public AuthToken(String token, long createTime) {
        this.token = token;
        this.createTime = createTime;
    }

    public AuthToken(String token, long createTime, long expiredTimeInterval) {
        this.token = token;
        this.createTime = createTime;
        this.expiredTimeInterval = expiredTimeInterval;
    }


    public boolean isExpired() {
        if (this.createTime > new Date().getTime() + expiredTimeInterval) {
            return true;
        }
        return false;
    }

    public boolean match(AuthToken authToken) {
        if (this.token.equals(authToken.token)) {
            return true;
        }
        return false;
    }

    public static AuthToken buildAuthToken(ApiRequest request, String password){
        // srcStr format:
        // "GETcvm.api.qcloud.com/v2/index.php?"
        //        + "AppID=AKIDz8krbsJ5yKBZQpn74WFkmLPx3gnPhESA"
        //        + "&Timestamp=1465185768";
        String srcStr = ""; // TODO
        srcStr = "test?"
                + "AppID=designpattern"
                + "&Timestamp=1465185768";
        String token = generateToken(srcStr, password);
        AuthToken authToken = new AuthToken(token);
        return authToken;
    }

    public String getToken() {
        return token;
    }

    public static String generateToken(String value, String key) {
        return hmacSha1(value, key);
    }


    private static String hmacSha1(String value, String key) {
        try {
            // Get an hmac_sha1 key from the raw key bytes
            byte[] keyBytes = key.getBytes();
            SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

            // Get an hmac_sha1 Mac instance and initialize with the signing key
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);

            // Compute the hmac on input data bytes
            byte[] rawHmac = mac.doFinal(value.getBytes());

            byte[] result = Base64.getEncoder().encode(rawHmac);

            //  Covert array of Hex bytes to a String
            return new String(result, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
